package com.github.prontera.web;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.prontera.util.Jacksons;
import com.google.common.collect.ImmutableMap;

import lombok.EqualsAndHashCode;

/**
 * @author Alex
 */
@EqualsAndHashCode
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler", "fieldHandler" }, ignoreUnknown = true)
public class ResponseDetailsLogger {

	@JsonIgnore
	private final HttpServletResponse response = ServletContextHolder.getResponse();

	@JsonProperty("headers")
	private ImmutableMap<String, Object> headers = fetchHttpHeaders(response);

	@JsonProperty("response_body")
	private Object responseBody;

	private ResponseDetailsLogger(Object responseBody) {
		this.responseBody = responseBody;
	}

	public static ResponseDetailsLogger with(Object responseBody) {
		return new ResponseDetailsLogger(responseBody);
	}

	private ImmutableMap<String, Object> fetchHttpHeaders(HttpServletResponse response) {
		final ImmutableMap.Builder<String, Object> headerBuilder = ImmutableMap.builder();
		for (String headerName : response.getHeaderNames()) {
			headerBuilder.put(headerName, response.getHeader(headerName));
		}
		return headerBuilder.build();
	}

	public ImmutableMap<String, Object> getHeaders() {
		return headers;
	}

	public void setHeaders(ImmutableMap<String, Object> headers) {
		this.headers = headers;
	}

	public Object getResponseBody() {
		return responseBody;
	}

	public void setResponseBody(Object responseBody) {
		this.responseBody = responseBody;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	@Override
	public String toString() {
		return Jacksons.parseInPrettyMode(this);
	}
}
